package com.open.cloud.rbac.service.user.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inspur.micro.core.utils.RSAUtil;
import com.inspur.micro.core.utils.SpringContextUtil;
import com.open.cloud.rbac.entity.config.CoreSystemConfig;
import com.open.cloud.rbac.entity.user.CoreUser;
import com.open.cloud.rbac.entity.user.CoreUserLoginInfo;
import com.open.cloud.rbac.jwt.Constants;
import com.open.cloud.rbac.jwt.JwtAccessToken;
import com.open.cloud.rbac.jwt.TokenResponse;
import com.open.cloud.rbac.jwt.TokenSSOProvider;
import com.open.cloud.rbac.mapper.config.CoreSystemConfigMapper;
import com.open.cloud.rbac.mapper.user.CoreUserLoginInfoMapper;
import com.open.cloud.rbac.mapper.user.CoreUserMapper;
import com.open.cloud.rbac.object.user.CoreLoginCheckCodeDto;
import com.open.cloud.rbac.object.user.CoreUserChangePwdDto;
import com.open.cloud.rbac.object.user.CoreUserDto;
import com.open.cloud.rbac.object.user.CoreUserLoginInfoDto;
import com.open.cloud.rbac.service.user.ICoreUserLoginInfoService;
import com.open.cloud.rbac.utils.RedisUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户登录信息 服务实现类
 * </p>
 *
 * @author wangzengzhou01
 * @since 2024-12-23
 */
@Service
public class CoreUserLoginInfoServiceImpl extends ServiceImpl<CoreUserLoginInfoMapper, CoreUserLoginInfo>
        implements ICoreUserLoginInfoService {

    @Value("${user.login.default.pwkey}")
    private String defaultPwKey;

    @Value("${user.login.default.password}")
    private String defaultPassword;

    @Value("${user.login.default.checkCode}")
    private Integer checkCodeExpire;

    @Value("${user.login.default.errorNum}")
    private Integer errorNum;

    @Resource
    private CoreSystemConfigMapper systemConfigMapper;

    @Resource
    private CoreUserLoginInfoMapper userLoginInfoMapper;

    @Resource
    private CoreUserMapper userMapper;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 账户操作信息
     *
     * @param userDto
     * @return
     */
    @Override
    public JSONObject userLoginInfoChange(CoreUserDto userDto) {

        LambdaQueryWrapper<CoreUserLoginInfo> loginQuery = Wrappers.<CoreUserLoginInfo>lambdaQuery()
                .eq(CoreUserLoginInfo::getUserLoginName, userDto.getUserLoginName())
                .eq(CoreUserLoginInfo::getId, userDto.getUserLoginId())
                .ne(CoreUserLoginInfo::getStatus, "4");
        List<CoreUserLoginInfo> loginList = userLoginInfoMapper.selectList(loginQuery);

        JSONObject result = new JSONObject();
        if (loginList.size() > 0) {
            CoreUserLoginInfo userLoginInfo = new CoreUserLoginInfo();
            userLoginInfo.setId(userDto.getUserLoginId());
            if (userDto.getOperate().equals("resetPwd")) {
                String defaultPwd = defaultPassword;
                QueryWrapper sysQuery = Wrappers.<CoreSystemConfig>query()
                        .eq("config_key", defaultPwKey);
                CoreSystemConfig systemConfig = systemConfigMapper.selectOne(sysQuery);
                if (ObjectUtils.isNotEmpty(systemConfig)) {
                    defaultPwd = systemConfig.getConfigValue();
                }
                userLoginInfo.setInitPasswordFlag("1");
                userLoginInfo.setUserLoginPassword(DigestUtil.md5Hex(defaultPwd));
            }
            if (userDto.getOperate().equals("delete")) {
                userLoginInfo.setStatus("4");
            }
            int update = userLoginInfoMapper.updateById(userLoginInfo);
            if (update > 0) {
                result.put("code", 200);
                result.put("message", "操作成功");
            } else {
                result.put("code", 500);
                result.put("message", "操作失败");
            }
        } else {
            result.put("code", 500);
            result.put("message", "用户不存在，操作失败");
        }
        return result;
    }

    /**
     * 修改密码
     *
     * @param changePwdDto
     * @return
     */
    @Override
    public JSONObject changeLoginPassword(CoreUserChangePwdDto changePwdDto) {
        String password = DigestUtil.md5Hex(changePwdDto.getOldPassword());
        LambdaQueryWrapper<CoreUserLoginInfo> loginQuery = Wrappers.<CoreUserLoginInfo>lambdaQuery()
                .eq(CoreUserLoginInfo::getUserLoginName, changePwdDto.getUserLoginName())
                .eq(CoreUserLoginInfo::getUserLoginPassword, password)
                .ne(CoreUserLoginInfo::getStatus, "4");

        CoreUserLoginInfo loginInfo = userLoginInfoMapper.selectOne(loginQuery);
        loginInfo.setInitPasswordFlag("0");
        loginInfo.setUserLoginPassword(DigestUtil.md5Hex(changePwdDto.getNewPassword()));
        int update = userLoginInfoMapper.updateById(loginInfo);
        JSONObject result = new JSONObject();
        if (update > 0) {
            result.put("code", 200);
            result.put("message", "修改成功");
        } else {
            result.put("code", 500);
            result.put("message", "修改失败");
        }
        return result;
    }

    /**
     * 接收验证码
     *
     * @param checkCodeDto
     * @return
     */
    @Override
    public JSONObject saveCheckCode(CoreLoginCheckCodeDto checkCodeDto) {
        String uuid = checkCodeDto.getUuid();
        String checkCode = checkCodeDto.getCheckCode();
        redisUtil.set("LOGIN_CODE_" + uuid, checkCode, checkCodeExpire);
        JSONObject result = new JSONObject();
        result.put("code", 200);
        result.put("message", "成功");
        return result;
    }

    /**
     * 用户登录校验
     *
     * @param userLoginInfoDto
     * @return
     */
    @Override
    public JSONObject checkLoginInfo(CoreUserLoginInfoDto userLoginInfoDto) {
        String loginName = userLoginInfoDto.getLoginName();

        String loginFailRedisKey = "LOGIN_" + loginName;
        String userFailNumObj = (String) redisUtil.get(loginFailRedisKey);
        Integer userFailNum = 0;
        JSONObject result = new JSONObject();
        if (ObjectUtils.isNotEmpty(userFailNumObj)) {
            userFailNum = Integer.parseInt(userFailNumObj);
            if (userFailNum >= errorNum) {
                long time = redisUtil.getTime(loginFailRedisKey);
                String tmpTime = time + "秒";
                if (time >= 60) {
                    tmpTime = time / 60 + "分钟" + time % 60 + "秒";
                }
                String message = "用户名或密码错误超过" + errorNum + "次数限制,请" + tmpTime + "后再试";
                result.put("code", 591);
                result.put("message", message);
                return result;
            }
        }
        // 验证码输入
        String textCode = userLoginInfoDto.getCheckCode();
        String checkCodeKey = "LOGIN_CODE_" + userLoginInfoDto.getUuid();
        String checkCode = (String) redisUtil.get(checkCodeKey);
        if (StrUtil.isEmpty(checkCode)) {
            result.put("code", 592);
            result.put("message", "请先获取图片验证码");
            return result;
        }
        if (!checkCode.equalsIgnoreCase(textCode)) {
            result.put("code", 593);
            result.put("message", "图片验证码不正确");
            return result;
        }
        redisUtil.delKey(checkCodeKey);
//        String encryptPwd = userLoginInfoDto.getPassword();
//        String password = RSAUtil.decrypt(encryptPwd);
        String password = userLoginInfoDto.getPassword();
        LambdaQueryWrapper<CoreUserLoginInfo> loginQuery = Wrappers.<CoreUserLoginInfo>lambdaQuery()
                .eq(CoreUserLoginInfo::getUserLoginName, loginName)
                .ne(CoreUserLoginInfo::getStatus, "4");
        CoreUserLoginInfo userLoginInfo = userLoginInfoMapper.selectOne(loginQuery);

        if (ObjectUtils.isEmpty(userLoginInfo)) {
            result.put("code", 594);
            result.put("message", "账号不存在");
            return result;
        }

        userLoginInfo.setUpdateTime(new Date());
        userLoginInfo.setLastLoginTime(new Date());

        if (!userLoginInfo.getUserLoginPassword().equals(password)) {
            result.put("code", 595);
            Integer times = userFailNum + 1;
            String message = "用户名或密码错误,已登录错误次数为" + times + "次，剩余" + (errorNum - times) + "次登录机会";
            userLoginInfo.setLoginFailTimes(userLoginInfo.getLoginFailTimes() + 1);
            if (times >= errorNum) {
                userLoginInfo.setStatus("2");
                userLoginInfo.setLockType("loginFail");
                userLoginInfoMapper.updateById(userLoginInfo);
                message = "用户名或密码错误,已登录错误次数为" + errorNum + "次请" + 30 + "分钟再试";
            }
            redisUtil.set(loginFailRedisKey, times + "", 1800);//1800秒
            result.put("message", message);
            return result;
        }

        if (userLoginInfo.getStatus().equals("2") || userLoginInfo.getStatus().equals("3")) {
            userLoginInfo.setLoginFailTimes(userLoginInfo.getLoginFailTimes() + 1);
            userLoginInfoMapper.updateById(userLoginInfo);
            result.put("code", 596);
            result.put("message", "登录失败，请联系管理员");
            return result;
        }

        if (userLoginInfo.getInitPasswordFlag().equals("1")) {
            userLoginInfo.setLoginFailTimes(userLoginInfo.getLoginFailTimes() + 1);
            userLoginInfoMapper.updateById(userLoginInfo);
            result.put("code", 597);
            result.put("message", "密码为初始密码，请修改");
            return result;
        }

        redisUtil.set(loginFailRedisKey, 0 + "", 1800);//1800秒

        LambdaQueryWrapper<CoreUser> userQuery = Wrappers.<CoreUser>lambdaQuery()
                .eq(CoreUser::getUserLoginId, userLoginInfo.getId());
        CoreUser coreUser = userMapper.selectOne(userQuery);
        TokenResponse token = createToken(coreUser, userLoginInfo.getUserLoginName());

        JSONObject data = new JSONObject();
        data.put("userInfo", coreUser);
        data.put("token", token);

        result.put("code", 200);
        result.put("data", data);
        return result;
    }

    /**
     * 生成token
     *
     * @param coreUserVo
     * @return
     */
    public TokenResponse createToken(CoreUser coreUserVo, String loginName) {
        JwtAccessToken jwtAccessToken = new JwtAccessToken();
        jwtAccessToken.setIss("Inspur");
        Map<String, Object> params = new HashMap<>();
        params.put(Constants.LOGIN_USER_ID, coreUserVo.getId());
        params.put(Constants.LOGIN_ACCOUNT_ID, coreUserVo.getUserLoginId());
        params.put(Constants.LOGIN_USER_NAME, coreUserVo.getNickName());
        params.put(Constants.LOGIN_ACCOUNT_NAME, loginName);
        params.put(Constants.LOGIN_LOGINNAME, loginName);
        Environment env = SpringContextUtil.getBean(Environment.class);
        long expiredTime = Long.parseLong(env.getProperty("user.token.expired"));
        TokenSSOProvider tokenProvider = SpringContextUtil.getBean(TokenSSOProvider.class);
        TokenResponse tokenResponse = tokenProvider.createToken(jwtAccessToken, expiredTime, params);
        return tokenResponse;
    }


}
